package dao.impl;

import dao.IBookDao;
import pojo.Book_info;
import util.DBHelper;
import util.PageHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BookDaoImpl implements IBookDao {
    DBHelper db=new DBHelper();
    @Override
    public ArrayList<Book_info> selectAll() {
        String sql="select * from book_info";
        return db.dtQuery(sql,Book_info.class);
    }

    @Override
    public int countSelectByType(Integer book_type) {
        StringBuilder sql = new StringBuilder("select count(book_id) from book_info where 1=1");
        ArrayList<Object> params = new ArrayList<>();

        if (book_type != null && book_type >= 0) {
            sql.append(" and book_type = ?");
            params.add(book_type);
        }

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            con = db.getCon();
            ps = con.prepareStatement(sql.toString());

            // 设置参数
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }

            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                return resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            db.closeAll(con, ps, resultSet);
        }
        return 0;
    }

    @Override
    public ArrayList<Book_info> selectByType(Integer book_type, PageHelper pageHelper) {
        StringBuilder sql = new StringBuilder("select * from book_info where 1=1");
        ArrayList<Object> params = new ArrayList<>();

        if (book_type != null && book_type >= 0) {
            sql.append(" and book_type = ?");
            params.add(book_type);
        }

        sql.append(" limit ?, ?");

        // 修正数学运算：先计算括号内的乘法，再减法
        int index = (pageHelper.getPageIndex() - 1) * pageHelper.getShowNumber();
        params.add(index);
        params.add(pageHelper.getShowNumber());

        System.out.println("SQL: " + sql.toString());
        System.out.println("参数: " + params);

        return db.dtQuery(sql.toString(), Book_info.class, params.toArray());
    }

    @Override
    public ArrayList<Book_info> selectByName(String book_name) {
        String sql="select * from book_info where book_name=?";
        return db.dtQuery(sql,Book_info.class,book_name);
    }

    @Override
    public ArrayList selectByStatus(Integer is_borrow) {
        String sql="select * from book_info where is_borrow=?";
        return db.dtQuery(sql,Book_info.class,is_borrow);
    }

    @Override
    public int updateStatusById(Integer book_id,Integer is_borrow) {
        String sql="update book_info set is_borrow=? where book_id=?";
        Object[] objs={is_borrow,book_id};
        return db.dtUpdate(sql,objs);
    }
}
